<?php

namespace App\Admin\Controllers;

use App\Models\RateType;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use function foo\func;

class RateTypeController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('速率曲线');
            $content->description('');
            $content->row(view('admin.lineChart'));
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('速率曲线');
            $content->description('');

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('速率曲线');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {

        return Admin::grid(RateType::class, function (Grid $grid) {

            if (!request()->get('_sort')) $grid->model()->orderByDesc('id');
            $grid->id('ID')->sortable();
            $grid->column('title','曲线名称');
            $grid->column('data','曲线数据')->display(function($value){
                $data = json_decode($value);
                if($data) $value = implode(',',$data);
                return <<<EOF
              <span class="lineChartRender">$value</span>
EOF;
            });
            $grid->column('enable','启用')->switch(config('system.switch.states'));
            $grid->created_at('创建时间')->sortable();
//            $grid->updated_at('更新时间');
            $grid->filter(function (Grid\Filter $filter){
                $filter->like('title','曲线名');
                $filter->equal('enable','启用')->select([1=>'启用',2=>'禁用']);
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Admin::form(RateType::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('title','曲线名称')->rules('required');
            $form->highchart('data','速率曲线');
            $form->switch('enable','启用')->states(config('system.switch.states'))->default(1);
            $form->display('created_at', 'Created At');
            $form->display('updated_at', 'Updated At');
        });
    }

}
